import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login'
import Home from '../components/Home'
import Index from '../components/Index'
import Article from '../components/Article'
import Publish from '../components/Publish'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Index,
    children: [
      {
        path: '/',
        component: Home,
        name: Home
      },
      {
        path: '/article',
        component: Article,
        name: Article
      },
      {
        path: '/publish',
        component: Publish,
        name: Publish
      }
    ]
  },
  {
    path: '/login',
    component: Login
  }
]

const router = new VueRouter({
  routes
})

// 配置路由守卫
router.beforeEach((to, from, next) => {
  // 判断是否去登录页
  if (to.path !== '/login') {
    const user = JSON.parse(window.localStorage.getItem('user'))
    // 判断是否已经登录
    if (user) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
